<template>
  <basic-container>
    <el-row>
      <!--      <el-col :span="4">-->
      <!--        <el-tabs type="border-card">-->
      <!--          <el-tab-pane label="储位管理列表" class="informationLabel">-->
      <!--            <avue-tree-->
      <!--              class="treeList"-->
      <!--              :option="treeOption"-->
      <!--              :data="treeData"-->
      <!--              @node-click="nodeClick"-->
      <!--              :default-expanded-keys="expandedKeys"-->
      <!--              highlight-current="true"-->
      <!--              ref="treeProperties"-->
      <!--            />-->
      <!--          </el-tab-pane>-->
      <!--        </el-tabs>-->
      <!--      </el-col>-->
      <el-col :span="4">
        <el-tabs type="border-card">
          <el-tab-pane label="储位管理列表" class="informationLabel">
            <el-tree
              class="treeList"
              lazy
              :load="loadNode"
              :props="props"
              node-key="id"
              :option="treeOption"
              :expand-on-click-node="false"
              :data="treeData"
              @node-click="nodeClick"
              :default-expanded-keys="expandedKeys"
              :current-node-key="currentNodeKey"
              :highlight-current="true"
              ref="treeProperties"
            />
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <!-- <el-col :span="1"></el-col> -->
      <el-col :span="20">
        <div style="margin-left: 10px">
          <el-tabs type="border-card" style="margin-bottom: 20px">
            <el-tab-pane label="储位管理查询" class="informationLabel">
              <avue-form ref="formOptionRef" :option="headerFormOption" v-model="headerForm">
                <template slot-scope="{ size }" slot="menuForm">
                  <el-button type="primary" icon="el-icon-search" :size="size" @click="searchChange">搜索</el-button>
                  <el-button :size="size" icon="el-icon-delete" @click="searchReset">清空</el-button>
                </template>
              </avue-form>
            </el-tab-pane>
          </el-tabs>
          <el-tabs type="border-card">
            <el-tab-pane label="储位管理详情" class="informationLabel">
              <avue-crud
                :option="option"
                :table-loading="loading"
                v-model="form"
                :data="itemData"
                :page.sync="page"
                :permission="permissionList"
                :before-open="beforeOpen"
                ref="crud"
                @current-change="currentChange"
                @size-change="sizeChange"
                @on-load="onLoad"
                @row-del="handleDelete"
                @tree-load="treeLoadData"
              >
                <template slot-scope="{ row }" slot="status">
                  <el-tag :class="row.status ? 'successTag' : 'dangerTag'">{{ row.status ? '是' : '否' }}</el-tag>
                </template>
                <template slot="menuLeft">
                  <el-button
                    type="primary"
                    :disabled="selectTreeItem.areaType == 'STORAGE' || (!selectTreeItem.id && !selectTreeItem.areaType)"
                    size="small"
                    icon="el-icon-plus"
                    v-if="permission.storage_addArea"
                    @click="add('STORAGE_AREA')"
                    >新建区域</el-button
                  >
                  <el-button
                    type="primary"
                    :disabled="selectTreeItem.areaType != 'STORAGE_AREA'"
                    size="small"
                    icon="el-icon-plus"
                    v-if="permission.storage_addStorage"
                    @click="add('STORAGE')"
                    >新建储位</el-button
                  >
                  <el-dropdown @command="handleSelectItem">
                    <el-button type="success" size="small" icon="el-icon-upload2">导入</el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="area">区域导入</el-dropdown-item>
                      <el-dropdown-item command="storage">储位导入</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <!--                  <el-button type="success" size="small" icon="el-icon-position" @click="handleImportArea">导入区域</el-button>-->
                  <!--                  <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImportStorage">导入储位</el-button>-->
                </template>
                <!--                <template slot="menuRight">-->
                <!--                  <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
                <!--                </template>-->
                <template slot="menu" slot-scope="{ row }">
                  <!-- <el-button type="text" icon="el-icon-view" size="small" @click="viewDetail(row.id)">查看</el-button> -->
                  <el-button type="text" icon="el-icon-edit" size="small" @click="update(row.id, row.areaType)">编辑</el-button>
                  <!--                  <el-button type="text" icon="el-icon-delete" size="small" @click="handleDelete(row)">删除</el-button>-->
                  <el-button type="text" icon="el-icon-printer" size="small" v-if="row.areaType === 'STORAGE'" @click="handlePrint(row)">打印</el-button>
                </template>
              </avue-crud>
            </el-tab-pane>
          </el-tabs>
          <el-dialog :title="attributeTitle" append-to-body :visible.sync="showAttributeDialog" width="60%" @close="closeDialog">
            <avue-form ref="attributeProperties" v-model="model" :option="attributeOption">
              <template slot="menuForm">
                <div style="float: right; margin-right: 70px">
                  <!-- <el-button size="medium" v-if="attributeCode != 'view'" type="primary" @click="submit">提交</el-button>
                      <el-button size="medium" @click="cancelAttribute">取消</el-button> -->
                </div>
              </template>
            </avue-form>
            <span slot="footer" class="dialog-footer">
              <el-button
                type="primary"
                size="small"
                :icon="attributeCode == 'add' ? 'el-icon-circle-plus-outline' : 'el-icon-circle-check'"
                v-if="attributeCode != 'view'"
                @click="submit"
                >{{ attributeCode == 'add' ? '保 存' : '修 改' }}</el-button
              >
              <el-button size="small" icon="el-icon-circle-close" @click="cancelAttribute">取 消</el-button>
            </span>
          </el-dialog>
          <el-dialog append-to-body :title="title" v-if="printInfoModel" :visible.sync="printInfoModel" width="35%">
            <avue-form ref="printForm" v-model="printInfo" :option="printInfoOption"> </avue-form>
            <span slot="footer" class="dialog-footer">
              <el-button size="small" type="primary" @click="printSubmit"><i class="el-icon-printer"></i><span>打 印</span></el-button>
              <el-button size="small" @click="printInfoModel = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
            </span>
          </el-dialog>
          <importDialogComp
            :title="importConfig.title"
            :url="importConfig.url"
            :export-name="importConfig.exportName"
            :visible.sync="importConfig.show"
            @submit="codeClose"
          ></importDialogComp>
        </div>
      </el-col>
    </el-row>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import { add, getAreaTree, getDetail, getInventoryList, print, remove } from '@/api/admin/storage';
import { validateContacts } from '@/mixins/validateContacts.js';
import importDialogComp from '@/components/dialog/import/index.vue';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';

const validateColor = (rule, value, callback) => {
  if (value != null && value.length > 12) {
    callback(new Error('颜色长度不能超过12'));
  } else {
    callback();
  }
};
export default {
  name: 'AdminStorage',
  components: {
    importDialogComp,
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  inject: ['reload'],
  data() {
    return {
      pageCode: 'ADMIN_STORAGE',
      importConfig: {
        title: '',
        url: '',
        exportName: '',
        show: false
      },
      currentkey: '',
      modalName: '',
      selectTreeItem: {},
      tableOption: {},
      treeTypes: [],
      expandedKeys: [], //树形默认展开节点
      currentNodeKey: '',
      resolve: '',
      printInfoModel: false,
      printInfo: {},
      timer: new Date().getTime(),
      disabledAttributeControl: false,
      treeData: [],
      props: {
        labelText: '标题',
        label: 'label',
        value: 'value',
        children: 'children',
        isLeaf: 'leaf'
      },
      treeOption: {
        nodeKey: 'id',
        lazy: true,
        treeLoad: function (node, resolve) {
          if (node.data.length === 0) {
            return [];
          }
          if (!node.data.value.areaType) {
            getAreaTree({ inventoryId: node.data.id, parentId: node.data.id }).then((res) => {
              resolve(
                res.data.data
                  .filter((item) => item.areaType == 'STORAGE_AREA')
                  .map((item) => {
                    return {
                      label: item.name,
                      id: item.id,
                      ...item,
                      value: item,
                      leaf: !item.hasChildren
                    };
                  })
              );
              this.loading = false;
            });
          }
          if (node.data.value.areaType === 'STORAGE_AREA') {
            getAreaTree({ parentId: node.data.id }).then((res) => {
              resolve(
                res.data.data.map((item) => {
                  return {
                    label: item.name,
                    id: item.id,
                    ...item,
                    value: item,
                    leaf: item.areaType === 'STORAGE'
                  };
                })
              );
              this.loading = false;
            });
          }
        },
        menu: false,
        filter: false,
        size: 'small',
        props: {
          labelText: '标题',
          label: 'label',
          value: 'value',
          children: 'children'
        }
      },
      itemData: [],
      headerForm: {
        name: '',
        code: ''
      },
      headerFormOption: {
        menuSpan: 6,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '名称',
            prop: 'name',
            span: 6
          },
          {
            label: '编码',
            prop: 'code',
            span: 6
          }
        ]
      },
      option: {
        lazy: true,
        height: 'calc(100vh - 434px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: false,
        addBtn: false,
        delBtn: true,
        viewBtn: true,
        viewBtnText: '详情',
        viewTitle: '详情',
        editBtn: false,
        refreshBtn: false,
        selection: false,
        dialogClickModal: false,
        labelWidth: 120,
        menuWidth: 250,
        searchLabelWidth: 90,
        columnBtn: false,
        column: [
          {
            label: '名称',
            prop: 'name',
            maxlength: 32,
            sortable: true,
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '编码',
            prop: 'code',
            maxlength: 32,
            sortable: true,
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '类型',
            prop: 'areaType',
            type: 'select',
            dicUrl: `/api/blade-system/dict/dictionary?code=area_type`,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '物料存储类型',
            prop: 'partCategories',
            multiple: true, //是否多选
            checkStrictly: true, //在显示复选框的情况下，是否严格的遵循父子不相互关联的做法
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '颜色标识',
            prop: 'color',
            type: 'color', //增加颜色选择器
            showAlpha: false,
            rules: [
              {
                required: false,
                trigger: 'blur',
                validator: validateColor
              }
            ]
          },
          {
            label: '启用',
            prop: 'status',
            type: 'switch',
            value: 1,
            dataType: 'number',
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 3 //定义多行文本最小行数
          }
        ]
      },
      printInfoOption: {
        labelWidth: 150,
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '打印机',
            prop: 'equipmentName',
            span: 20,
            type: 'search',
            placeholder: '请选择 打印机',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择打印机',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPrintersModal();
            }
          },
          {
            label: '标签模版',
            prop: 'labelTemplateName',
            span: 20,
            type: 'search',
            placeholder: '请选择 标签模板',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择标签模板',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLabelTemplateModal();
            }
          }
        ]
      },
      loading: true,
      selectTreeNode: {},
      selectNode: [],
      attributeTitle: '',
      attributeIds: [],
      attributeCode: '', //判断为编辑、增加、查看
      showAttributeDialog: false,
      model: {}, //检验项对象
      //检验项配置
      attributeOption: {
        emptyBtn: false,
        submitBtn: false,
        column: []
      }
    };
  },
  watch: {
    attributeCode(val) {
      this.disabledAttributeControl = val === 'view';
    }
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$structuralSplit();
    this.initTree();
  },
  methods: {
    //id为默认展开的id
    initTree(id) {
      this.treeData = [];
      getInventoryList().then((res) => {
        this.treeData = (res.data.data || []).map((item) => {
          let treeItem = {
            leaf: !item.hasChildrenArea,
            value: item,
            label: item.name,
            id: item.id
          };
          return treeItem;
        });
        // this.$nextTick(() => {
        //   id ? (this.expandedKeys = [].concat([id])) : [];
        //   id ? this.$refs.treeProperties.setCurrentKey(`${id}`) : '';
        // });
      });
    },
    async loadNode(node, resolve) {
      this.resolve = resolve;
      if (node.data.length === 0) {
        return [];
      }

      if (!node.data.value.areaType) {
        // this.loading = true;
        await getAreaTree({ inventoryId: node.data.id, parentId: node.data.id })
          .then((res) => {
            resolve(
              res.data.data
                .filter((item) => item.areaType == 'STORAGE_AREA')
                .map((item) => {
                  return {
                    label: item.name,
                    id: item.id,
                    ...item,
                    value: item,
                    leaf: !item.hasChild
                  };
                })
            );
            // this.itemData = this._cloneDeep(res.data.data) || [];
            // this.loading = false;
          })
          .catch((e) => {
            resolve([]);
          });
      } else if (node.data.value.areaType === 'STORAGE_AREA') {
        // this.loading = true;
        await getAreaTree({ parentId: node.data.id })
          .then((res) => {
            //  this.itemData = this._cloneDeep(res.data.data) || [];
            resolve(
              res.data.data.map((item) => {
                return {
                  label: item.name,
                  id: item.id,
                  ...item,
                  value: item,
                  leaf: item.areaType === 'STORAGE'
                };
              })
            );
            // this.loading = false;
          })
          .catch((e) => {
            resolve([]);
          });
      }
    },
    nodeClick(data, node, self) {
      this.selectNode = node;
      // 防止重复加载
      if (Object.keys(this.selectTreeItem).length > 0 && this.selectTreeItem.id === data.value.id) {
        return;
      }
      this.selectTreeItem = data.value;
      if (!data.value.areaType) {
        this.loading = true;
        getAreaTree({ inventoryId: data.id, parentId: data.id })
          .then((res) => {
            this.itemData = (res.data.data || [])
              .filter((item) => item.areaType === 'STORAGE_AREA')
              .map((item) => {
                return item;
              });
          })
          .finally(() => {
            this.loading = false;
          });
        //点击储位只需展示此储位信息
      } else if (data.value.areaType == 'STORAGE') {
        this.loading = true;
        getDetail(data.id)
          .then((res) => {
            this.itemData = ([res.data.data] || []).map((item) => {
              return item;
            });
          })
          .finally(() => {
            this.loading = false;
          });
      } else if (data.value.areaType == 'STORAGE_AREA') {
        getAreaTree({ id: data.id })
          .then((res) => {
            this.itemData = (res.data.data || []).map((item) => {
              return item;
            });
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    //懒加载区域与储位表格树
    treeLoadData(tree, treeNode, resolve) {
      getAreaTree({ parentId: tree.id }).then((res) => {
        // this.itemData = (res.data.data || []).map((item) => {
        //   return item;
        // });
        resolve(res.data.data || []);
      });
    },

    getSelectedRows(rowData, title) {
      switch (this.modalName) {
        case 'labelTemplateModal':
          this.$set(this.printInfo, 'labelTemplateId', rowData.id);
          this.$set(this.printInfo, 'labelTemplateName', rowData.fileName);
          break;
        case 'printersModal':
          this.$set(this.printInfo, 'equipmentId', rowData.id);
          this.$set(this.printInfo, 'equipmentName', rowData.name);
          break;
        default:
          break;
      }
    },

    beforeOpen(done, type) {
      done();
    },

    onLoad(page, params = {}) {
      this.loading = false;
    },

    //增加
    add(key) {
      let partCategoriesUrl = this.selectTreeItem.partCategories
        ? `/api/mes-admin/part-category/tree?partCategories=${this.selectTreeItem.partCategories}`
        : `/api/mes-admin/part-category/tree`;
      let column =
        key === 'STORAGE_AREA'
          ? [
              {
                label: '名称',
                labelWidth: 110,
                prop: 'name',
                maxlength: 32,
                rules: [
                  {
                    required: true,
                    message: '请输入名称',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '编码',
                prop: 'code',
                maxlength: 32,
                rules: [
                  {
                    required: true,
                    message: '请输入编码',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '物料存储类型',
                labelWidth: 110,
                prop: 'partCategories',
                multiple: true, //是否多选
                checkStrictly: true, //在显示复选框的情况下，是否严格的遵循父子不相互关联的做法
                type: 'tree',
                dicUrl: partCategoriesUrl,
                props: {
                  label: 'title',
                  value: 'id'
                }
              },
              {
                label: '负责人',
                prop: 'principal',
                type: 'select',
                dicUrl: `/api/blade-system/user/user-list`,
                props: {
                  label: 'name',
                  value: 'id'
                }
              },
              {
                label: '联系方式',
                prop: 'contacts',
                labelWidth: 110,
                rules: [{ validator: validateContacts, trigger: 'blur' }]
              },
              {
                label: '启用',
                prop: 'status',
                type: 'switch',
                value: 1,
                dataType: 'number',
                dicData: [
                  {
                    label: '否',
                    value: 0
                  },
                  {
                    label: '是',
                    value: 1
                  }
                ]
              },
              {
                label: '备注',
                prop: 'remark',
                labelWidth: 110,
                type: 'textarea',
                minRows: 3 //定义多行文本最小行数
              }
            ]
          : [
              {
                label: '名称',
                prop: 'name',
                maxlength: 32,
                rules: [
                  {
                    required: true,
                    message: '请输入名称',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '编码',
                labelWidth: 110,
                prop: 'code',
                maxlength: 32,
                rules: [
                  {
                    required: true,
                    message: '请输入编码',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '颜色标识',
                prop: 'color',
                type: 'color', //增加颜色选择器
                colorFormat: 'hex',
                showAlpha: false,
                rules: [
                  {
                    required: false,
                    trigger: 'blur',
                    validator: validateColor
                  }
                ]
              },
              {
                label: '物料存储类型',
                labelWidth: 110,
                prop: 'partCategories',
                multiple: true, //是否多选
                checkStrictly: true, //在显示复选框的情况下，是否严格的遵循父子不相互关联的做法
                type: 'tree',
                dicUrl: partCategoriesUrl,
                props: {
                  label: 'title',
                  value: 'id'
                }
              },

              {
                label: '空间位置',
                prop: 'location',
                type: 'select',
                dicUrl: '/api/blade-system/dict/dictionary?code=Spatial_Location',
                props: {
                  label: 'dictValue',
                  value: 'dictKey'
                }
              },
              {
                label: '启用',
                prop: 'status',
                type: 'switch',
                value: 1,
                dataType: 'number',
                dicData: [
                  {
                    label: '否',
                    value: 0
                  },
                  {
                    label: '是',
                    value: 1
                  }
                ]
              },
              {
                label: '备注',
                prop: 'remark',
                type: 'textarea',
                minRows: 3 //定义多行文本最小行数
              }
            ];
      this.attributeOption.column = column;
      this.model.status = 1;
      this.attributeCode = 'add';
      this.attributeTitle = '添加';
      this.showAttributeDialog = true;
      this.model.areaType = key;
    },
    update(id, areaType) {
      let partCategoriesUrl = this.selectTreeItem.partCategories
        ? `/api/mes-admin/part-category/tree?partCategories=${this.selectTreeItem.partCategories}`
        : `/api/mes-admin/part-category/tree`;

      let column =
        areaType === 'STORAGE_AREA'
          ? [
              {
                label: '名称',
                prop: 'name',
                maxlength: 32,
                labelWidth: 110,
                rules: [
                  {
                    required: true,
                    message: '请输入名称',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '编码',
                prop: 'code',
                maxlength: 32,
                rules: [
                  {
                    required: true,
                    message: '请输入编码',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '物料存储类型',
                labelWidth: 110,
                prop: 'partCategories',
                multiple: true, //是否多选
                checkStrictly: true, //在显示复选框的情况下，是否严格的遵循父子不相互关联的做法
                type: 'tree',
                dicUrl: partCategoriesUrl,
                props: {
                  label: 'title',
                  value: 'id'
                }
              },
              {
                label: '负责人',
                prop: 'principal',
                type: 'select',
                dicUrl: `/api/blade-system/user/user-list`,
                props: {
                  label: 'name',
                  value: 'id'
                }
              },
              {
                label: '联系方式',
                prop: 'contacts',
                labelWidth: 110,
                rules: [{ validator: validateContacts, trigger: 'blur' }]
              },
              {
                label: '启用',
                prop: 'status',
                type: 'switch',
                value: 1,
                dataType: 'number',
                dicData: [
                  {
                    label: '否',
                    value: 0
                  },
                  {
                    label: '是',
                    value: 1
                  }
                ]
              },
              {
                label: '备注',
                prop: 'remark',
                labelWidth: 110,
                type: 'textarea',
                minRows: 3 //定义多行文本最小行数
              }
            ]
          : [
              {
                label: '名称',
                prop: 'name',
                maxlength: 32,
                rules: [
                  {
                    required: true,
                    message: '请输入名称',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '编码',
                prop: 'code',
                maxlength: 32,
                labelWidth: 110,
                rules: [
                  {
                    required: true,
                    message: '请输入编码',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '颜色标识',
                prop: 'color',
                type: 'color', //增加颜色选择器
                colorFormat: 'hex',
                showAlpha: false,
                rules: [
                  {
                    required: false,
                    trigger: 'blur',
                    validator: validateColor
                  }
                ]
              },
              {
                label: '物料存储类型',
                labelWidth: 110,
                prop: 'partCategories',
                multiple: true, //是否多选
                checkStrictly: true, //在显示复选框的情况下，是否严格的遵循父子不相互关联的做法
                type: 'tree',
                dicUrl: partCategoriesUrl,
                props: {
                  label: 'title',
                  value: 'id'
                }
              },

              {
                label: '空间位置',
                prop: 'topMiddleBottom',
                type: 'select',
                dicUrl: '/api/blade-system/dict/dictionary?code=Spatial_Location',
                props: {
                  label: 'dictValue',
                  value: 'dictKey'
                }
              },
              {
                label: '启用',
                prop: 'status',
                type: 'switch',
                value: 1,
                dataType: 'number',
                dicData: [
                  {
                    label: '否',
                    value: 0
                  },
                  {
                    label: '是',
                    value: 1
                  }
                ]
              },
              {
                label: '备注',
                prop: 'remark',
                type: 'textarea',
                minRows: 3 //定义多行文本最小行数
              }
            ];
      this.attributeOption.column = column;
      this.attributeCode = 'edit';
      this.attributeTitle = '编辑';

      getDetail(id).then((res) => {
        this.model = res.data.data;
        this.showAttributeDialog = true;
        // }
      });
    },

    viewDetail(id) {
      this.attributeCode = 'view';
      this.attributeTitle = '查看';
      getDetail(id).then((res) => {
        this.model = res.data.data;
        this.showAttributeDialog = true;
        // }
      });
    },

    //新增或修改
    async submit() {
      let model = this._cloneDeep(this.model);
      if (model.partCategories && Array.isArray(model.partCategories)) {
        model.partCategories = model.partCategories.join(',');
      }
      if (this.attributeCode === 'add') {
        model.inventoryId = this.selectTreeItem.areaType ? this.selectTreeItem.inventoryId : this.selectTreeItem.id;
        model.parentId = this.selectTreeItem.id;
        model.id = '';
      }

      let done;
      let validDate = await new Promise((resolve, reject) => {
        this.$refs.attributeProperties.validate((valid, done) => {
          done = done;
          if (valid) {
            resolve();
            done();
          } else {
          }
        });
      });
      Promise.all([validDate]).then(() => {
        add(model).then(
          async (res) => {
            // this.itemData = [];
            // this.selectTreeItem = {};
            // this.$message({
            //   type: 'success',
            //   message: '操作成功!'
            // });
            // this.showAttributeDialog = false;
            // this.initTree(model.id);
            // this.$nextTick(() => {
            //   this.$refs.attributeProperties.resetForm();
            // });
            this.itemData = [];
            await this.getTable(this.selectNode.data);
            this.setStoreTreeNode(res.data.data, this.attributeCode);
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.$refs.attributeProperties.resetForm();
            this.showAttributeDialog = false;
            // this.loading = true;
            // this.$refs.attributeProperties.resetForm();
            // // this.$refs.attributeProperties.resetForm();
            // this.showAttributeDialog = false;
            // // this.expandedKeys = [this.selectTreeItem.id];
            // console.log(this.selectNode);
            // // await this.loadNode(this.selectNode, this.resolve);
            // const nodeData = this.$refs.treeProperties.getNode(this.selectTreeItem.id);
            // this.itemData = nodeData.childNodes.map((item) => item.data);
            // this.loading = false;
          },
          (error) => {
            console.log(error);
            window.console.log(error);
          }
        );
      });
    },
    getTable(data) {
      if (!data.areaType) {
        this.loading = true;
        getAreaTree({ inventoryId: data.id, parentId: data.id })
          .then((res) => {
            this.itemData = (res.data.data || [])
              .filter((item) => item.areaType === 'STORAGE_AREA')
              .map((item) => {
                return item;
              });
          })
          .finally(() => {
            this.loading = false;
          });
        //点击储位只需展示此储位信息
      } else if (data.areaType == 'STORAGE') {
        this.loading = true;
        getDetail(data.id)
          .then((res) => {
            this.itemData = ([res.data.data] || []).map((item) => {
              return item;
            });
          })
          .finally(() => {
            this.loading = false;
          });
      } else if (data.areaType == 'STORAGE_AREA') {
        getAreaTree({ id: data.id })
          .then((res) => {
            this.itemData = (res.data.data || []).map((item) => {
              return item;
            });
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    //取消
    cancelAttribute() {
      // this.$nextTick(() => {
      //   this.$refs.attributeProperties.resetForm();
      // });
      this.$refs.attributeProperties.resetForm();
      this.model = {};
      this.showAttributeDialog = false;
      // this.$refs.attributeProperties.resetForm();
    },

    closeDialog() {
      this.$refs.attributeProperties.resetForm();
    },
    handlePrint(row) {
      this.printInfo.id = row.id;
      this.printInfo.name = row.name;
      this.printInfo.code = row.code;
      this.printInfoModel = true;
    },
    setStoreTreeNode(node, type) {
      this.selectNode.isLeaf = false;
      const childNode = {
        id: node.id,
        label: node.name,
        key: node.id,
        leaf: !node.hasChildren,
        value: node
      };
      if (type === 'add') {
        this.$refs.treeProperties.append(childNode, this.selectNode);
      } else {
        const newArray = this.selectNode.childNodes.map((item) => {
          item.id = item.data.id;
          if (item.data.id === node.id) {
            item.data = childNode;
            item.value = node;
            return item; // 用新的对象替换匹配的对象
          } else {
            item.value = item.data;
          }
          return item; // 返回原始对象
        });
        this.$nextTick(() => {
          this.$refs.treeProperties.updateKeyChildren(this.selectNode.data.id, newArray);
        });
      }
    },
    /*
     * 打印
     */
    printSubmit() {
      this.$refs.printForm.validate((valid, done) => {
        if (valid) {
          let params = {
            name: this.printInfo.name,
            code: this.printInfo.code,
            id: this.printInfo.id,
            printId: this.printInfo.equipmentId,
            labelTemplateId: this.printInfo.labelTemplateId
          };
          print(params).then(
            (res) => {
              this.$refs.printForm.resetFields();
              this.printInfoModel = false;
              this.$message({
                type: 'success',
                message: res.data.msg
              });
              done();
            },
            (error) => {
              done();
            }
          );
        }
      });
    },
    handleDelete(row, index, done) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove([row.id]);
        })
        .then(async () => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done(row);
          this.$refs.treeProperties.remove(row);
        });
    },

    // removeNode(treeArray, targetId) {
    //   return treeArray.reduce((result, item) => {
    //     if (item.id !== targetId) {
    //       const newItem = { ...item }; // 创建新的对象副本
    //       if (item.children && item.children.length > 0) {
    //         newItem.children = this.removeNode(item.children, targetId); // 递归处理子节点
    //       }
    //       result.push(newItem); // 添加到新数组中
    //     }
    //     return result;
    //   }, []);
    // },
    handleImportArea() {
      this.importConfig.show = true;
      this.importConfig.url = '/api/mes-admin/area/import-area';
      this.importConfig.exportName = '区域导入模板.xlsx';
      this.importConfig.title = '区域导入';
    },
    handleImportStorage() {
      this.importConfig.show = true;
      this.importConfig.url = '/api/mes-admin/area/import-storage';
      this.importConfig.exportName = '储位导入模板.xlsx';
      this.importConfig.title = '储位导入';
    },
    codeClose(value) {
      if (value) {
        this.reload();
      }
    },
    handleSelectItem(command) {
      command === 'area' ? this.handleImportArea() : this.handleImportStorage();
    },
    searchReset() {
      this.headerForm.code = this.headerForm.name = '';
      this.handleHeaderFormSearch(this.headerForm.code, this.headerForm.name);
    },
    searchChange() {
      if (!this.selectTreeItem.id) {
        this.$message.warning('请先选择仓库后再进行搜索');
        return false;
      }
      this.handleHeaderFormSearch(this.headerForm.code, this.headerForm.name);
    },
    handleHeaderFormSearch(code, name) {
      if (!this.selectTreeItem.areaType) {
        this.loading = true;
        getAreaTree({ inventoryId: this.selectTreeItem.id, parentId: this.selectTreeItem.id, code: code, name: name })
          .then((res) => {
            this.itemData = (res.data.data || [])
              .filter((item) => item.areaType === 'STORAGE_AREA')
              .map((item) => {
                return item;
              });
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        this.loading = true;
        getAreaTree({ id: this.selectTreeItem.id, code: code, name: name })
          .then((res) => {
            this.itemData = (res.data.data || []).map((item) => {
              return item;
            });
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 获取打印机
     */
    openPrintersModal() {
      this.modalName = 'printersModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择打印机（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '打印机编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 110
          },
          {
            label: '打印机名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 110
          }
        ]
      };
    },
    /**
     * 打开标签模板模态框
     */
    openLabelTemplateModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模版（双击进行选择）',
        url: '/api/mes-admin/labeltemplate/page?status=1',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '标签名称',
            prop: 'fileName',
            search: true
          },
          {
            label: '标签代码',
            prop: 'code',
            search: true
          },
          {
            label: '版本名称',
            prop: 'revision'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl'
          },
          {
            label: '打印标签',
            prop: 'fileUrl'
          }
        ]
      };
    }
  }
};
</script>

<style lang="scss" scoped>
.box {
  height: 800px;
}

.el-scrollbar {
  height: 100%;
}

.box .el-scrollbar__wrap {
  overflow: scroll;
}

.icon-inspection-item {
  font-size: 18px;
}
.refresh-item {
  background: #00bcd4;
}

.add-item {
  background: #4caf50;
}

.edit-item {
  background: #077fc1;
}

.del-item {
  background: #f44336;
}

.refresh-item,
.add-item,
.edit-item,
.del-item {
  margin-right: 8px;
  cursor: pointer;
  color: #ffffff;
}

::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid #f0f0f0;
  padding: 10px 16px;
}
::v-deep .el-dialog {
  .avue-form__menu {
    display: none;
  }
}
::v-deep .el-tabs__item {
  color: #606266 !important;
  font-weight: bold;
}
::v-deep .el-card__body {
  padding: 10px;
}
::v-deep .el-card .is-never-shadow {
  padding: 0;
}
.treeList {
  height: calc(100vh - 226px);
  border-top: 1px solid #cccccc;
  overflow-y: scroll;
}
::v-deep .el-tree-node__content {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  height: 30px;
  cursor: pointer;
  border: 1px solid #cccccc;
  border-top: none;
}
::v-deep .avue-tree__content {
  padding: 0;
}
</style>
